import mqtt from 'mqtt'
import { getValue } from '@/libs/util'
import store from '../store/index'

import { encrypt, encryptOne, decrypt, cuttingValue, stringToByte, HexString2Bytes, byteToString, decryptone } from './util'
import { _pullUserRequest, _getFriendsResult, _userResult, _userRequest, _pullGroupInfoResult } from '../pbApi/pb_WFCMessage'
let client = null
let wsUrl = 'ws://13.75.118.184:8083' //开发地址
// let wsUrl = 'ws://120.77.173.90:8083'  //90环境
// let wsUrl = 'ws://120.25.77.97:8083' //97环境

// 进来默认解密的key
let secret = '001122334455667778797a7b7c7d7e7f'
class mqtts {
    // 初始化mqtt
    initMqtt() {
            // // 第一次解密token
            var decrypted = decrypt(getValue('loginInfo').token, byteToString(HexString2Bytes(secret)), byteToString(HexString2Bytes(secret)))
                // // 拿到密码和key加密传回后台
            var password = encrypt(stringToByte(cuttingValue(decrypted).pwd), cuttingValue(decrypted).key, cuttingValue(decrypted).key)
                // 参数
            var options = {
                connectTimeout: 40000,
                clientId: getValue('client').clientId,
                username: getValue('loginInfo').userId,
                password: password,
                clean: true
            }
            client = mqtt.connect(wsUrl, options)
                // mqtt连接
            client.on('connect', (e) => {
                    this.mqttConnect(e)
                })
                // 接收消息处理
            client.on('message', (topic, message) => {
                    this.mqttMessage(topic, message)
                })
                // 断开发起重连
            client.on('reconnect', (error) => {
                    // console.log('正在重连:', error)
                    this.mqttReconnect(error)
                })
                // 链接异常处理
            client.on('error', (error) => {
                // console.log('连接失败:', error)
                this.mqttError(error)
            })
        }
        // 断开
    mqttDisconnect() {
            console.log('断开')
            client.end()
        }
        // 成功连接返回
    mqttConnect(e) {
            console.log("连接成功", e)
            store.commit('CONNECT_ACK_PAYLOAD', e.payload)
            this.mqttSuccess()
        }
        // 发送消息
    mqttPublish(topic, msg, callback) {
            // 第一次解密token
            var decrypted = decrypt(store.state.user.token, byteToString(HexString2Bytes(secret)), byteToString(HexString2Bytes(secret)))
                // 拿到密码和key加密传回后台
            var key = cuttingValue(decrypted).key
            if (topic == 'MP' || topic == 'FP') {
                var msgs = encryptOne(msg, key, key)
            } else {
                var msgs = encrypt(msg, key, key)
            }
            client.publish(topic, msgs, { qos: 1 }, (code, packet) => {
                if (packet.qos == 0) {
                    if (packet.payload[0] == 0) {
                        let bytes = decryptone(packet.payload.slice(1), key, key)
                        callback(bytes,packet.payload[0])
                    }else if(packet.payload[0] == 1){
                        callback(bytes,packet.payload[0])
                    }
                }
            })
        }
        // 接受消息处理
    mqttMessage(topic, message) {
            let msg = {
                topic: topic,
                msg: message
            }
            store.commit('RECEIVE_MSG', msg)
        }
        // 断开重连
    mqttReconnect(error) {
            console.log("断开：", error)
        }
        // 连接异常处理
    mqttError(error) {
            console.log("异常:", error)
        }
        // 连接成功
    mqttSuccess() {
        // 个人用户信息
        this.mqttPublish('UPUI', _pullUserRequest([_userRequest(store.state.user.userId)]), (data) => {
                // 用户信息
                let userInfo = _userResult(data)
                store.commit('setUserInfo', userInfo[0])
            })
            // 获取好友通讯录
        store.dispatch('FRIEND_LIST')
    }
}

const mqt = new mqtts()

export default mqt